package edu.hawaii.ics314.ical.view;

import java.util.ArrayList;
import java.util.Objects;
import java.util.Scanner;

public abstract class AbstractView<T> implements View<T> {
	
	protected final ArrayList<ViewListener<T>> LISTENERS = new ArrayList<ViewListener<T>>();
	protected Scanner consoleReader = null;

	@Override
	public void addViewListener(ViewListener<T> listener) {
		LISTENERS.add(Objects.requireNonNull(listener));
	}

	@Override
	public void removeViewListener(ViewListener<T> listener) {
		LISTENERS.remove(Objects.requireNonNull(listener));
	}
	
	protected void fireOnViewResult(T result, int index) {
		ViewEvent<T> evt = new ViewEvent<T>(this, result, index);
		for(ViewListener<T> listener : LISTENERS) {
			listener.onViewResult(evt);
		}
	}
	
	protected String readStdinLine() {
		if(consoleReader == null) {
			// Intentionally not closing the scanner because it is connected to System.in.
			consoleReader = new Scanner(System.in);
		}
		return consoleReader.nextLine();
	}

}
